import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Lesson5 {

    /**
     *  使用定制的Executor在前一个阶段上异步应用函数
     *
     *  异步方法一个非常有用的特性就是能够提供一个Executor来异步地执行CompletableFuture。
     *  这个例子演示了如何使用一个固定大小的线程池来应用大写函数。
     * */

    private static AtomicInteger atomicInteger = new AtomicInteger(1);

    private static ExecutorService executorService = new ThreadPoolExecutor(10, 10, 1, TimeUnit.HOURS, new ArrayBlockingQueue(10), r -> {
        Thread thread = new Thread(r);
        thread.setDaemon(true);
        thread.setName("custom-executor-" + atomicInteger.incrementAndGet());
        return thread;
    });

    public static void main(String[] args) {
        CompletableFuture completableFuture =  CompletableFuture
                .completedFuture("message")
                .thenApplyAsync(s -> {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName());
                    return s.toUpperCase();
                }, executorService);
        System.out.println(completableFuture.getNow(null));
        completableFuture.join();
        System.out.println(completableFuture.getNow(null));
    }
}
